#!/usr/bin/env node

const {
  openUrl,
  setItem,
  importFile,
  getUrlFromkey,
  getItem
} = require("./util");
const fs = require("fs");
var args = process.argv.splice(2); // 把node 和 位置两个参数 干掉
// 1 如果 不是import 那么 判断是不是 url u
const type = args[0];
if (type === "import") {
  const path = args[1];
  importFile(path);
} else if (type === "set") {
  const key = args[1];
  const url = args[2];
  setItem(key, url);
} else if (type === "show") {
  const obj = getItem();
  console.log(JSON.stringify(obj, null, 2));
} else if (type === "npm") {
  try {
    const content = fs.readFileSync("./package.json", {
      encoding: "utf-8"
    });
    const obj = JSON.parse(content);
    const packageName = obj["name"];
    const url = `https://www.npmjs.com/package/${packageName}`;
    openUrl(url);
  } catch (err) {
    console.log("读取文件出错，当前工程没有package.json文件", err);
  }
} else {
  const key = args[0];
  const url = getUrlFromkey(key);
  if (url !== undefined) {
    openUrl(url);
  } else {
    console.error("key值不存在");
  }
}
